<%@ page contentType="text/html" pageEncoding="UTF-8"%>
<% response.setContentType("text/html; charset=UTF-8");%>
<% request.setCharacterEncoding("utf-8");%>
<%@ page import="java.sql.*" %>
<%@ page import="javax.xml.parsers.*" %>
<%@ page import="org.w3c.dom.*" %>
<%@ page import="java.io.File" %>
<%
	Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new File(getServletContext().getRealPath("/") + "web.xml"));
	doc.getDocumentElement().normalize();
	String dbhost = doc.getElementsByTagName("host").item(0).getTextContent();
	String dbport = doc.getElementsByTagName("port").item(0).getTextContent();
	String dbuser = doc.getElementsByTagName("user").item(0).getTextContent();
	String dbpass = doc.getElementsByTagName("pass").item(0).getTextContent();
	String dbname = doc.getElementsByTagName("database").item(0).getTextContent();
	String dbconnString = "jdbc:mysql://" + dbhost + ":" + dbport + "/" + dbname + "?setUnicode=true&characterEncoding=UTF-8";
	Class.forName("com.mysql.jdbc.Driver").newInstance();
	Connection dbconn = DriverManager.getConnection(dbconnString, dbuser, dbpass);
	Statement query = dbconn.createStatement();
	Statement query2 = dbconn.createStatement();
%>

<%
	/*
	getParameter unicode với GET method 
	chỉnh file conf/server.xml của tomcat
	thêm 2 parameter sau vào Connector
	<Connector port="8080" ...
		URIEncoding="UTF-8"
		useBodyEncodingForURI="true" />
	*/

	String hoten = request.getParameter("hoten");
	String cmnd = request.getParameter("cmnd");
	String ngaysinh = request.getParameter("ngaysinh");
	ResultSet rs = null, rs2 = null;
	try {
		rs = query.executeQuery("select * from thisinh where cmnd = '" + cmnd + "'");
		if (!rs.next()) // CMND chưa tồn tại
		{
			try {
				query.executeUpdate("insert into thisinh (hoten, cmnd, ngaysinh) values ('" + hoten + "' , '" + cmnd + "' , '" + ngaysinh + "')");
			} catch (Exception e) {
				out.print("0"); // lỗi insert
			}
			rs2 = query2.executeQuery("select * from thisinh where cmnd = '" + cmnd + "'");
			rs2.next();
			HttpSession ss = request.getSession();
			ss.setAttribute("type", "TS"); // thí sinh
			ss.setAttribute("maTS", rs2.getInt("maTS"));
			ss.setAttribute("hoten", rs2.getString("hoten"));
			ss.setAttribute("isLogin", true);
			rs2.close();
			out.print("2"); // đăng ký thành công
		} else {
			out.print("1"); // CMND đã tồn tại
		}
	} catch (Exception e) {
		out.print("0"); // lỗi select
	}
	rs.close();

%>

<% dbconn.close();%>